package com.wanban.m3u8download

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.ImageLoader
import coil.executeBlocking
import coil.request.ImageRequest
import com.wanban.download.DefaultDownloadManager
import com.wanban.download.WBDownloadUtils
import com.wanban.download.db.DownloadEntity
import com.wanban.download.listener.OnLoadCoverImageListener
import com.wanban.download.model.Status
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.io.FileOutputStream

class MainActivity : Activity() {

    private lateinit var recyclerView: RecyclerView
    private val downloadList = ArrayList<DownloadEntity>()
    private val downloadAdapter by lazy { DownloadAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        recyclerView = findViewById(R.id.recyclerView)

        recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        recyclerView.adapter = downloadAdapter
        downloadAdapter.itemAnimation = null
        downloadAdapter.animationEnable = false
        EventBus.getDefault().register(this)
        // 初始化数据库
        WBDownloadUtils.init(application) { tasks ->
            val downloadTasks = DataUtils.getDownloads()
            tasks.forEach { task ->
                for (entity in downloadTasks) {
                    if (task.url == entity.url) {
                        entity.percent = task.percent
                        entity.contentLength = task.contentLength
                        entity.state = task.state
                    }
                }
            }
            downloadList.addAll(downloadTasks)
            downloadAdapter.submitList(downloadList)

            WBDownloadUtils.resumeAllDownloads()
        }.setOnLoadCoverImageListener(object: OnLoadCoverImageListener {
            override fun onLoadCoverImageAsync(coverUrl: String, coverFile: File) {
                try {
                    val request = ImageRequest.Builder(this@MainActivity)
                        .data(coverUrl)
                        .build()
                    val imageLoader = ImageLoader.Builder(this@MainActivity)
                        .build()
                    val drawable = imageLoader.executeBlocking(request).drawable?:return
                    val bitmap = (drawable as BitmapDrawable).bitmap
                    if (coverFile.exists() && coverFile.length() > 0) {
                        return
                    }
                    FileOutputStream(coverFile).use { outStream ->
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    coverFile.delete()
                }
            }
        })

        downloadAdapter.addOnItemChildClickListener(R.id.btn_start) { adapter, view, position ->
            val item = adapter.getItem(position)?:return@addOnItemChildClickListener
            WBDownloadUtils.startDownload(item)
        }

        downloadAdapter.addOnItemChildClickListener(R.id.btn_stop) { adapter, view, position ->
            val item = adapter.getItem(position)?:return@addOnItemChildClickListener
            WBDownloadUtils.stopDownload(item.url)
        }

        downloadAdapter.addOnItemChildClickListener(R.id.btn_resume) { adapter, view, position ->
            val item = adapter.getItem(position)?:return@addOnItemChildClickListener
            WBDownloadUtils.resumeDownload(item.url)
        }

        downloadAdapter.addOnItemChildClickListener(R.id.btn_delete) { adapter, view, position ->
            val item = adapter.getItem(position)?:return@addOnItemChildClickListener
            WBDownloadUtils.deleteDownload(item.url)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDownloadEvent(event: DownloadEntity) {
        val index = downloadList.indexOfFirst { it.url == event.url }
        if (index < 0) return

        if (event.state == Status.DELETE) {
            event.speed = 0
            event.contentLength = 0
            event.percent = 0f
            event.state = Status.IDLE
            event.m3u8 = null
        } else if (event.state == Status.STOP) {
            event.speed = 0
        }
        downloadList[index] = event
        downloadAdapter.notifyItemChanged(index)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
